/*
 * Texture.cpp
 *
 *  Created on: May 9, 2013
 *      Author: zapmunk
 */

#include "headerstop.h"

#include "Texture.h"
#include "GLLib.h"

Texture::Texture(const SDL_Surface *const surf):
		persistant(new PersistantTexture(surf)),
		w(persistant->width), h(persistant->height),
		tex(persistant->tex),
		//tex_format(persistant->tex_format),
		tex_colors(persistant->tex_colors) {}

Texture::Texture(const Texture& other):
		persistant(other.persistant),
		w(persistant->width), h(persistant->height),
		tex(persistant->tex),
		//tex_format(persistant->tex_format),
		tex_colors(persistant->tex_colors) {}
Texture& Texture::operator=(const Texture& other) {
	return *this = Texture(other);
}

void Texture::clean() {
	delete persistant;
}

Texture::PersistantTexture::PersistantTexture(const SDL_Surface *const surf) throw(const char*) {
	if (!surf) throw "Null surface specified!";

	width = surf->w;
	height = surf->h;

	if (surf->format->BytesPerPixel == 4) {
		if (surf->format->Rmask == 0x000000ff)
			tex_colors = GL_RGBA;
		else
			tex_colors = GL_BGRA;
	} else if (surf->format->BytesPerPixel == 3) {
		if (surf->format->Rmask == 0x000000ff)
			tex_colors = GL_RGB;
		else
			tex_colors = GL_BGR;
	} else {
		throw "Surface not truecolor!";
	}

	GL::glGenTextures(1, &tex);
	GL::glBindTexture(GL_TEXTURE_2D, tex);
	GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	GL::glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	GL::glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
	GL::glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
	GL::glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, tex_colors, GL_UNSIGNED_BYTE, surf->pixels);
}

Texture::PersistantTexture::~PersistantTexture() {
	GL::glDeleteTextures(1, &tex);
}
